package key;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.SQLException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class Madd
 */
@WebServlet("/Madd")
public class Madd extends HttpServlet {
	private static final long serialVersionUID = 1L;

	Log log = new Log();
	Database db = new Database();
	
    public Madd() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String uname = request.getParameter("uname");
		String tidS = request.getParameter("tid");
		int tid = Integer.parseInt(tidS);
		int uid = 0;
		String uidS = null;
		try{
			uidS = db.getUid(uname);
		}catch(SQLException e){
			log.writeIn("Madd: 不存在此用户或页面出现错误0022");
		}
		if(uidS != null){
		uid = Integer.parseInt(uidS);
		db.madd(uid, tid);
		
		/* 生成页面 */
		response.setContentType("text/html;charset=utf-8");
		PrintWriter out = response.getWriter();
		response.setCharacterEncoding("utf-8");
		out.println("<html>\n<head>\n<title>提示信息</title>\n</head>\n<body>");
		out.println("<script type='text/javascript'>\nconfirm('添加成功')");
		out.println("window.location.href='master/index.jsp';\n</script>");
		out.println("</body>\n</html>");
		
//		response.sendRedirect("master/index.jsp");
//		@SuppressWarnings("unused")
//		Frame fr = new Frame("添加成功");
		}else{
			
			/* 生成页面 */
			response.setContentType("text/html;charset=utf-8");
			PrintWriter out = response.getWriter();
			response.setCharacterEncoding("utf-8");
			out.println("<html>\n<head>\n<title>提示信息</title>\n</head>\n<body>");
			out.println("<script type='text/javascript'>\nconfirm('不存在此用户或出现错误')");
			out.println("window.location.href='master/index.jsp';\n</script>");
			out.println("</body>\n</html>");
			
			/*生成错误页面*/
//			response.sendRedirect("master/index.jsp");
//			@SuppressWarnings("unused")
//			Frame fr = new Frame("不存在此用户或出现错误");
		}
		
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}
